package org.ruoyi.dhuman.utils;

import cn.hutool.http.HttpDownloader;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.mbeans.MBeanUtils;
import org.ruoyi.common.core.utils.StringUtils;
import org.ruoyi.common.dhuman.ppt.PPTContent;
import org.ruoyi.common.dhuman.ppt.PPTProcessor;
import org.ruoyi.common.dhuman.ppt.SlideContent;
import org.ruoyi.common.dhuman.utils.DocumentToImagesUtils;
import org.ruoyi.common.oss.core.OssClient;
import org.ruoyi.common.oss.entity.UploadResult;
import org.ruoyi.common.oss.factory.OssFactory;
import org.ruoyi.dhuman.vo.UploadResult2;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
//import javazoom.jl.decoder.JavaLayerException;
//import javazoom.jl.player.Player;
//
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;

@Slf4j
public class CommonUtils {
	public static List<UploadResult2> uploadPPT(String workpath, MultipartFile file, String ocrLanguagePath) throws Exception {
		// 创建以时间戳命名的文件夹
		String timestamp = new java.text.SimpleDateFormat("yyyyMMdd.HHmmss.SSS").format(new java.util.Date());
		String folderPath = workpath + "/ppt_" + timestamp;
		File folder = new File(folderPath);
		if (!folder.exists()) {
			folder.mkdirs();
		}

		// 将文件写入到本地文件系统
		File destFile = null;
		List<String> textContents = new ArrayList<>();
		if (file != null && !file.isEmpty()) {
			String originalFileName = file.getOriginalFilename();
			destFile = new File(folderPath + "/" + originalFileName);
			file.transferTo(destFile);


			// 内容识别
			try {
				PPTProcessor processor = new PPTProcessor();
				// 处理PPT文件
				PPTContent content = processor.processPPT(destFile.getAbsolutePath(), ocrLanguagePath);

				// 输出结果
				System.out.println("PPT总页数: " + content.getTotalSlides());
				System.out.println("=====================================");

				for (SlideContent slide : content.getSlides()) {
					System.out.println("第 " + slide.getSlideNumber() + " 页:");

					// 输出文字内容
					String textContent = slide.getTextContent();
					textContents.add(slide.getTextContent());
					System.out.println("文字内容:");
					System.out.println(textContent);

					// 输出图片OCR结果
//					if (!slide.getImages().isEmpty()) {
//						System.out.println("图片识别结果:");
//						for (int i = 0; i < slide.getImages().size(); i++) {
//							ImageContent image = slide.getImages().get(i);
//							System.out.println("图片 " + (i + 1) + " OCR结果:");
//							System.out.println(image.getOcrText());
//						}
//					}

					System.out.println("-------------------------------------");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}


		}

		List<File> files = new ArrayList<>();
		if (destFile != null) {
			List<BufferedImage> images = DocumentToImagesUtils.extractPagesAsImages(destFile);
			String path = destFile.getParent();
			// 保存图片到磁盘
			files = DocumentToImagesUtils.saveImagesToDisk(path, images, destFile.getName());
		}

		List<UploadResult2> uploadResults = new ArrayList<>();
		OssClient storage = OssFactory.instance();
		for (int i = 0; i < files.size(); i++) {
			File f = files.get(i);

			String originalfileName = f.getName();
			String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."),
				originalfileName.length());
			String contentType = "image/" + suffix.replace(".", "");
			UploadResult uploadResult = storage.uploadSuffix(new FileInputStream(f), suffix, contentType);

			String textContent = StringUtils.EMPTY;
			if (textContents.size() > i) {
				textContent = textContents.get(i);
			}
			UploadResult2 uploadResult2 = UploadResult2.builder().url(uploadResult.getUrl()).filename(uploadResult.getFilename()).textContent(textContent).build();
			uploadResults.add(uploadResult2);
		}

		return uploadResults;
	}

	public static UploadResult upload(File file) throws Exception {
		if (file == null || !file.exists()) {
			return null;
		}
		OssClient storage = OssFactory.instance();
		String originalfileName = file.getName();
		String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."),
			originalfileName.length());
		String contentType = "video/" + suffix.replace(".", "");
		UploadResult uploadResult = storage.uploadSuffix(new FileInputStream(file), suffix, contentType);

		return uploadResult;
	}

	public static String download(String url, String folderPath, String prefix) {
		try {
			File folder = new File(folderPath);
			if (!folder.exists()) {
				folder.mkdirs();
			}

			String fileName = url.substring(url.lastIndexOf("/") + 1);
			fileName = prefix + fileName;
			String filePath = folderPath + "/" + fileName;
			HttpDownloader.download(url, new FileOutputStream(filePath), true, null);
			log.info("文件下载成功: " + filePath);
			return fileName;
		} catch (Exception e) {
			String message = "文件下载失败, 地址：" + url;
			log.error(message, e);
			throw new RuntimeException(message);
		}
	}

//	private static Double getAudioDuration(File audioFile) {
//		if (audioFile == null || !audioFile.exists()) {
//			log.info("TTS音频文件不存在: " + audioFile);
//			return null;
//		}
//		// 获取音频时长的逻辑可以在这里添加
//		try {
//			FileInputStream fileInputStream = new FileInputStream(audioFile);
//			Player player = new Player(fileInputStream);
//			long duration = player.getMicrosecondLength() / 1000; // 获取微秒然后转换为毫秒
//			System.out.println("Duration: " + duration + " ms");
//			fileInputStream.close();
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (JavaLayerException e) {
//			e.printStackTrace();
//		} catch (FileNotFoundException e) {
//			throw new RuntimeException(e);
//		} catch (IOException e) {
//			throw new RuntimeException(e);
//		}
//	}
//
//	public static void main(String[] args) {
//		String url = "C:\\Users\\Admin\\Videos\\合并\\20251027.124447.681\\subPPT_0\\tts_1179119487945973760_1761290453.mp3";
//
//		Double duration = getAudioDuration(new File(url));
//		System.out.println(duration);
//	}
}
